#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

readonly redis_port=6379

readonly node_config_file=/etc/redis/redis_node.conf

# Get the list of Redis nodes
readonly nodes_attr="$(get_attribute_value "redis_node_hostnames")"
readonly persistent_nodes_attr="$(get_attribute_value "redis_persistent_nodes")"

readonly nodes=(${nodes_attr})
readonly nodes_count="${#nodes[@]}"

readonly master_node="${nodes[0]}"

persistent_nodes_count="${persistent_nodes_attr}"
if [[ "${persistent_nodes_attr}" == "-1" \
      || "${persistent_nodes_attr}" -ge "${nodes_count}" ]]; then
  persistent_nodes_count="$((nodes_count - 1))"
fi
persistent_nodes=(${nodes[@]:1:persistent_nodes_count})

declare -r persistent_nodes
declare -r persistent_nodes_count

echo "Nodes: ${nodes[*]}"
echo "Persistent nodes: ${persistent_nodes[*]}"

# Only set up persistent nodes if number of persistent nodes is gt 0.
if [[ "${persistent_nodes_count}" -gt 0 ]]; then
  for persistent_node in "${persistent_nodes[@]}"; do
    if [[ "$(hostname)" == "${persistent_node}" ]]; then
      echo "save 300 10" >> "${node_config_file}"
      echo "save 60 10000" >> "${node_config_file}"
    fi
  done
fi

# Set up slave nodes
if [[ "$(hostname)" != "${master_node}" ]]; then
  echo "Configuring slave mode on current node..."
  echo "slaveof ${master_node} ${redis_port}" >> "${node_config_file}"
fi

readonly sentinel_quorum="$((nodes_count / 2 + 1))"

export master_node
export sentinel_quorum

mkdir /var/run/redis

cd /etc/redis
envsubst < sentinel.conf.template > sentinel.conf
rm sentinel.conf.template

echo "Enabling both services: redis-server and redis-sentinel..."
systemctl daemon-reload
systemctl enable redis-server
systemctl enable redis-sentinel

echo "Starting redis-server service.."
systemctl start redis-server

echo "Starting redis-sentinel service.."
systemctl start redis-sentinel

# Wait until redis is up and running
until [[ "$(redis-cli ping)" == "PONG" ]]; do
  echo "Waiting for redis-cli to report PONG..." && sleep 5
done
